<template>
	<van-sticky>
		<van-nav-bar :title='title' :border='false' left-arrow @click-left="onClickLeft" />
	</van-sticky>
	<nut-searchbar v-model="searchValue" @change="onlyToSuggest">
		<template v-slot:rightout>
			<nut-button type="primary" color="#ffb5c5" @click="onSearch">搜索</nut-button>
		</template>
	</nut-searchbar>
	<keep-alive>
		<component :is="currentComponent" :data="data.data"></component>
	</keep-alive>
</template>

<script lang="ts" setup>
	import {
		ref,
		markRaw,
		onMounted,
		reactive
	} from 'vue'
	import SearchResult from '_c/search/SearchResult.vue'
	import SearchSuggest from '_c/search/SearchSuggest.vue'
	import router from '@/router'
	import {
		useCommStore
	} from "@/store/common.ts"
	import {
		storeToRefs
	} from 'pinia'
	const onClickLeft = () => history.back();

	const data = reactive({
		"data": []
	})

	// 获取查询关键字
	const searchValue = ref(router.currentRoute.value.query.searchkey)

	const store = useCommStore()
	// console.log(store)

	// 结构数据成为响应式数据
	const {
		recentSearch,
		other
	} = storeToRefs(store)

	// 切换搜索建议/搜索结果
	const lookup = {
		"SearchResult": SearchResult,
		"SearchSuggest": SearchSuggest
	}

	const currentComponent = ref(null)

	onMounted(() => {
		switchChild()
	})

	function switchChild() {
		console.log('switchChild')
		if (!searchValue.value) {
			changeToSuggest()
		} else {
			changeToResult()
		}
	}

	function onlyToSuggest() {
		console.log("change to suggest")
		if (!searchValue.value) {
			changeToSuggest()
		}
	}

	function onSearch() {
		console.log("获取搜索结果")
		store.saveRecentSearch(searchValue.value)
		console.log(store.getRecentSearch)
		if (!searchValue.value) {
			router.push({
				name: "search"
			})
			changeToSuggest()
		} else {
			router.push({
				name: "search",
				query: {
					"searchkey": searchValue.value
				}
			})
			changeToResult()
		}
	}

	function changeToSuggest() {
		console.log("跳转到Suggest")
		currentComponent.value = markRaw(lookup['SearchSuggest'])
	}

	function changeToResult() {
		console.log("跳转到Result")
		currentComponent.value = markRaw(lookup['SearchResult'])
		data.data = [{
				id: 1,
				title: "サキュバス喚んだら義母が来た!?",
				imgUrl: '../static/img/206-1.png',
				desc: "エンガワ卓&チンジャオ娘。の最強タッグが贈る「サキュバス喚んだら義母が来た!?」が待望のアニメ化！",
				tag: "动漫"
			},
			{
				id: 2,
				title: "サキュバス喚んだら義母が来た!?",
				imgUrl: "../static/img/206-1.png",
				desc: "エンガワ卓&チンジャオ娘。の最強タッグが贈る「サキュバス喚んだら義母が来た!?」が待望のアニメ化！",
				tag: "动漫"
			}
		]
	}
</script>

<style>
	:root {
		--van-nav-bar-background-color: #FFB5C5;
		--van-nav-bar-height: 72px;
		--van-nav-bar-title-text-color: white;
		--van-nav-bar-title-font-size: 20px;
		--van-nav-bar-arrow-size: 20px;
		}
	
	.van-icon-arrow-left {
		color: var(--nav-bar-icon-color, #FFF) !important;
	}
</style>
